package cn.chenhao.user.service.impl;

import cn.chenhao.basic.exception.BusinessException;
import cn.chenhao.basic.util.AjaxResult;
import cn.chenhao.basic.util.HttpClientUtils;
import cn.chenhao.basic.util.MD5Utils;
import cn.chenhao.basic.util.StrUtils;
import cn.chenhao.user.constant.UserConstant;
import cn.chenhao.user.domain.Logininfo;
import cn.chenhao.user.domain.User;
import cn.chenhao.user.domain.WxUser;
import cn.chenhao.user.dto.LoginDto;
import cn.chenhao.user.mapper.LogininfoMapper;
import cn.chenhao.user.mapper.UserMapper;
import cn.chenhao.user.mapper.WxUserMapper;
import cn.chenhao.user.service.ILoginService;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
@Service
public class LoginServiceImpl implements ILoginService {

    @Autowired
    private LogininfoMapper loginInfoMapper ;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private WxUserMapper wxUserMapper;

    @Autowired
    private UserMapper userMapper;

    /**
     * 用户注册业务流程
     * @param loginDto
     * @return
     */
    @Override
    public Map<String, Object> loginAccount(LoginDto loginDto) {
        // 一：校验
        // 1.账号，密码，账号类型的非空判断
        if(
                StringUtils.isEmpty(loginDto.getUsername())
                        || StringUtils.isEmpty(loginDto.getPassword())
                        || loginDto.getType() == null
        ){
            throw new BusinessException("请正确填写登录信息");
        }

        // 2.根据所填账号，查询是否已存在
        Logininfo logininfo =  loginInfoMapper.loginAccount(loginDto);
        if(logininfo == null){
            throw new BusinessException("该账户还未注册，请前往注册！");
        }

        // 二：密码验证
        String salt = logininfo.getSalt();
        String password = logininfo.getPassword();
        String encryp = MD5Utils.encrypByMd5(loginDto.getPassword() + salt);
        if(!password.equals(encryp)){// 比较输入的密码和数据库的密码是否一致
            throw new BusinessException("账号或密码输入错误，请重新输入！");
        }

        // 三：保存logininfo到redis中，token是key
        String token = UUID.randomUUID().toString();
        redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);// key是token，value是logininfo，有效期为30分钟

        // 四：通过map，将token返回给前端
        Map<String,Object> map = new HashMap<>();
        map.put("token", token);
        // 将敏感信息隐藏起来
        logininfo.setPassword(null);
        logininfo.setSalt(null);
        map.put("logininfo", logininfo);
        return map;
    }

    /**
     * 微信登录流程
     * @param map
     * @return
     */
    @Override
    public AjaxResult wechat(Map<String, String> map) {

        // 一：获取授权码
        String code = map.get("code");
        // 1.校验授权码
        if(!StringUtils.hasLength(code)){// 判断是否有权限，如果没有权限则提示用户去获取权限
            throw new BusinessException("您还未获得权限，请您联系微信客服，获取权限。");
        }

        // 2.如果有权限，则通过微信获取令牌token
        String wxuserGetTokenUrl = UserConstant.WXUSER_GET_TOKEN_URL
                .replace("APPID", UserConstant.APPID)
                .replace("SECRET", UserConstant.SECRET)
                .replace("CODE", code);

        String tokenObj = HttpClientUtils.httpGet(wxuserGetTokenUrl);// 获得回调域字符串

        // 通过阿里巴巴提供的工具类，将json字符串解析为json对象
        JSONObject jsonObject = JSONObject.parseObject(tokenObj);
        String accessToken = jsonObject.getString("access_token");// 拿到令牌
        String openId = jsonObject.getString("openid");// 拿到微信号

        /*System.err.println("令牌==============" + accessToken);
        System.err.println("微信号-------------" + openId);*/

        // 通过openId查询wxuser表中是否已存在
        WxUser wxUser = wxUserMapper.loadByOpenId(openId);

        // 判断当前用户是否已存在，并且是否已保存到我们系统用户表中
        if(wxUser != null && wxUser.getUser_id() != null){

            // 如果都存在，则免密直接登录
            Logininfo logininfo =  loginInfoMapper.loadByUserId(wxUser.getUser_id());

            // 三：保存logininfo到redis中，token是key
            String token = UUID.randomUUID().toString();
            redisTemplate.opsForValue().set(token,logininfo,30, TimeUnit.MINUTES);// key是token，value是logininfo，有效期为30分钟

            // 四：通过map，将token返回给前端
            Map<String,Object> maps = new HashMap<>();
            maps.put("token", token);
            // 将敏感信息隐藏起来
            logininfo.setPassword(null);
            logininfo.setSalt(null);
            maps.put("logininfo", logininfo);
            return AjaxResult.me().setResultObj(maps);
        }

        //4.如果找不到用户，说明是第一次扫码，前端应该跳转到绑定页面并携带token和openId回去
        String binderUrlParams = "?accessToken=" + accessToken + "&openId=" + openId;
        /*System.out.println(binderUrlParams);*/
        return AjaxResult.me().setSuccess(false).setResultObj(binderUrlParams);
    }

    @Override
    public Map<String, Object> binder(Map<String, String> params) {
        // 一：参数校验(手机号，验证码，微信号，授权码)
        // 非空判断
        String phone = params.get("phone");
        String verifyCode = params.get("verifyCode");
        String accessToken = params.get("accessToken");
        String openId = params.get("openId");
        if(!StringUtils.hasLength(phone)
            || !StringUtils.hasLength(verifyCode)
            || !StringUtils.hasLength(accessToken)
            || !StringUtils.hasLength(openId)
        ){
            throw new BusinessException("请正确输入账户信息！");
        }

        // 验证验证码是否过期
        Object codeTmp = redisTemplate.opsForValue().get(UserConstant.BUSINESS_BINDER_PREFIX + phone);
        if(codeTmp == null){
            throw new BusinessException("你的验证码已过期，请重新获取");
        }

        // 验证手机号是否已注册
        User userTmp = userMapper.loadByPhone(phone);
        User user = null;
        Logininfo logininfo = null;
        if(userTmp != null){// 如果查询不为空，则说明注册过，直接绑定
            user = userTmp;
            logininfo = loginInfoMapper.loadById(user.getLogininfo_id());
        } else {// 如果查询不到，则保存到我们的平台中
           user = initUser(phone);
            logininfo = user2Logininfo(user);
            loginInfoMapper.save(logininfo);
            user.setLogininfo_id(logininfo.getId());
            userMapper.save(user);
        }

        // 通过token和openid查询微信的用户信息
        String replace = UserConstant.WXUSER_GET_USER_URL
                .replace("ACCESS_TOKEN", accessToken)
                .replace("OPENID", openId);
        String wxUserTmp = HttpClientUtils.httpGet(replace);

        // 将获取到的微信用户信息保存到WxUser表，并绑定为平台用户
        WxUser wxUser = initWxUser(wxUserTmp,user);

        /*System.out.println(wxUser);*/

        wxUserMapper.save(wxUser);

        // 保存信息后，直接让当前用户免密登录，登录成功后，将token保存到redis中30分钟
        String token = UUID.randomUUID().toString();

        redisTemplate.opsForValue().set(
                token,
                logininfo,
                30,
                TimeUnit.MINUTES
        );

        // 通过map，将token返回给前端
        Map<String,Object> maps = new HashMap<>();
        maps.put("token", token);
        // 将敏感信息隐藏起来
        logininfo.setPassword("");
        logininfo.setSalt("");
        maps.put("logininfo", logininfo);
        return maps;
    }

    private WxUser initWxUser(String wxUserTmp, User user) {
        // 保存微信用户的信息
        JSONObject jsonObject = JSONObject.parseObject(wxUserTmp);
        WxUser wxUser =  new WxUser();
        wxUser.setUser_id(user.getId());//绑定用户
        wxUser.setOpenid(jsonObject.getString("openid"));
        wxUser.setNickname(jsonObject.getString("nickname"));
        wxUser.setSex(jsonObject.getInteger("sex"));
        wxUser.setAddress(jsonObject.getString("city"));
        wxUser.setHeadimgurl(jsonObject.getString("headimgurl"));
        wxUser.setUnionid(jsonObject.getString("unionid"));
        return wxUser;

    }

    private Logininfo user2Logininfo(User user) {
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user,logininfo);
        logininfo.setType(1);
        return logininfo;
    }

    private User initUser(String phone) {
        User user = new User();
        user.setUsername(phone);
        user.setPhone(phone);
        String salt = StrUtils.getComplexRandomString(32);
        String md5 = MD5Utils.encrypByMd5("1" + salt);
        user.setSalt(salt);
        user.setPassword(md5);
        return user;
    }
}
